package cn.itcast.web;

import cn.itcast.domain.Route;
import cn.itcast.service.RouteService;
import cn.itcast.service.RouteServiceImpl;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@WebServlet("/route")
public class Servlet extends HttpServlet {

    private RouteService routeService = new RouteServiceImpl();


    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if ("findAll".equals(method)) {
            findAll(req, resp);
        } else if ("addServlet".equals(method)) {
            addServlet(req, resp);
        } else if ("deleteServlet".equals(method)) {
            deleteServlet(req, resp);
        } else if ("updateFindById".equals(method)) {
            updateFindById(req, resp);
        } else if ("updateServlet".equals(method)) {
            updateFindById(req, resp);
        }
    }

    private void findAll(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setAttribute("list", routeService.findAll());
        req.getRequestDispatcher("/route_list.jsp").forward(req, resp);
    }


    private void addServlet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        try {
            Route route = new Route();
            BeanUtils.populate(route, req.getParameterMap());
            routeService.add(route);
            resp.sendRedirect(req.getContextPath() + "/findAll");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void deleteServlet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String rid = req.getParameter("rid");
        routeService.del(rid);
        resp.sendRedirect(req.getContextPath() + "/findAll");
    }


    private void updateFindById(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String rid = req.getParameter("rid");
        Route route = routeService.updateFindById(rid);
        req.setAttribute("route", route);
        req.getRequestDispatcher("/update.jsp").forward(req, resp);
    }


    private void updateServlet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            Route route = new Route();
            BeanUtils.populate(route, req.getParameterMap());
            routeService.update(route);
            resp.sendRedirect(req.getContextPath() + "/findAll");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
